import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios"
import _ from "lodash-es"
class Request {
  //axios实例
  private instance: AxiosInstance
  //默认配置
  private defaultConfig: AxiosRequestConfig
  constructor(prefix: string = "") {
    const baseURL = Request.checkHttp(prefix) ? prefix : `${import.meta.env.VITE_BASE_URL}/${prefix?.replace(/^\//, "")}`
    this.defaultConfig = {
      baseURL: baseURL,
      timeout: 10000, // 设置超时时间
      headers: {
        "Content-Type": "application/json",
      },
    }
    this.instance = axios.create(this.defaultConfig)

    // 请求拦截器
    this.instance.interceptors.request.use(
      (config: AxiosRequestConfig) => {
        const token = localStorage.getItem("token")
        if (token) {
          config.headers.Authorization = `Bearer ${token}`
        }
        return config
      },
      (error) => {
        return Promise.reject(error)
      },
    )

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        // 处理 200 状态码
        if (response.status === 200) {
          return response.data
        }
        return response.data
      },
      (error: AxiosError) => {
        const { response } = error
        if (response) {
          // 处理常见的 HTTP 状态码
          switch (response.status) {
            case 401:
              console.error("Unauthorized: Access denied")
              // 处理未授权，例如重定向到登录页面
              break
            case 404:
              console.error("Not Found: Resource not found")
              // 处理资源未找到
              break
            case 500:
              console.error("Internal Server Error: Something went wrong")
              // 处理服务器内部错误
              break
            default:
              console.error(`HTTP Error: ${response.status} - ${response.statusText}`)
              break
          }
        } else {
          // 处理网络错误或其他非 HTTP 错误
          console.error("Network Error:", error.message)
        }
        return Promise.reject(error)
      },
    )
  }

  public static checkHttp(url: string): boolean {
    const reg = /^(http|https):\/\//i
    return reg.test(url)
  }

  // GET 请求
  public async get<T>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> {
    const finalConfig = _.merge({}, this.defaultConfig, { params }, config)
    return this.instance.get<T>(url, finalConfig)
  }

  // POST 请求
  public async post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    const finalConfig = _.merge({}, this.defaultConfig, config)
    return this.instance.post<T>(url, data, finalConfig)
  }

  // PUT 请求
  public async put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    const finalConfig = _.merge({}, this.defaultConfig, config)
    return this.instance.put<T>(url, data, finalConfig)
  }

  // DELETE 请求
  public async delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    const finalConfig = _.merge({}, this.defaultConfig, config)
    return this.instance.delete<T>(url, finalConfig)
  }
}
export default Request
